(function(w){
    var opt = {
        getDoms : function(){
          this.doms = {
              time : $('.time'),
              MyPai : $('.MyPai'),
              leftPais : $('.leftPais'),
              RightPais : $('.RightPais'),
              mplay : $('.mplay'),
              MyPais : $('.MyPais'),
              audio : $('#audio'),
              mydata : $('#mydata'),
              leftdata : $('#leftdata'),
              leftdata : $('#rightdata'),
              dataId : $('.dataId'),
              blockpeng : $('#blockpeng'),
              mypengPai : $('.mypengPai')
          }
        },
        init : function(){
            var _self = this;
            _self.getDoms();
            _self.addEvent();
            _self.time();
            var urlData = w.location.href;
            var rid = urlData.split('/')[urlData.split('/').length-2];
            var mid = urlData.split('/')[urlData.split('/').length-1];
            var pasId = urlData.split('/')[urlData.split('/').length-3];
            urlData = ['tels',urlData.split('/')[urlData.split('/').length-3]]

            var roles = {
                host : ['r2','host','r1'],
                r1 : ['host','r1','r2'],
                r2 : ['r1','r2','host']
            };
            urlData =  roles[urlData[1]];
//            var k = _self.getHoom();//清空本地的牌
//            _self.clearStorage(k);清空本地的牌
            var wsServer ='ws://192.168.0.199:9502';  //地址
//            var wsServer ='ws://139.224.68.110:9502';  //地址
            ws = new WebSocket(wsServer); //监听链接
            ws.onopen = function (evt) {  //测试链接成功或失败
                //websocket.readyState 属性：
                switch (ws.readyState) {
                    case 0: console.log('通信服务未打开');break;
                    case 1: console.log('连接成功');break;
                    case 2: console.log('通信端口关闭，无法连接');break;
                    case 3: console.log('通信服务已关闭');break;
                }
                ws.send(JSON.stringify({
                    rid : rid,
                    role : pasId,
                    mid : mid,
                    type : 3
                }));
            };

            var cookiedata = _self.getStorage(_self);  //获取cookie里面是否有值
                ws.onmessage = function (evt) { //返回数据

                    var evtData = JSON.parse(evt.data);
                    if(evtData.type==3){
                            if(evtData.playlist!=undefined){
                                var key = _self.getHoom();
                                _self.displayCp(urlData, evt.data,_self);
                                var parseJson = JSON.parse(evt.data);
                                var name = new Array();
                                name.push(
                                    {
                                        jsonList: []
                                    },
                                    {
                                        payrest: []
                                    },
                                    {
                                        data: []
                                    }
                                );
                                name[1].payrest.push(parseJson.playlist.payrest);
                                name[2].data.push(parseJson);
                                _self.getcookie(name, key);
                                _self.templateMy(_self, evt.data, urlData[1]);
                                _self.templateLeft(_self, evt.data, urlData[0]);
                                _self.templateRight(_self, evt.data, urlData[2]);
                            };
                    }
                    if(evtData.type==5){
                        if(evtData.cid) {
                            if (urlData[1] == evtData.next) {
                                _self.overpais($('.leftoverpais'), evtData.cid, 'l');
                            }
                            if (urlData[1] != evtData.next) {
                                _self.overpais($('.rightoverpais'), evtData.cid, 'r');
                            }
                        }
                        var roles = {
                            host: ['r2', 'host', 'r1'],
                            r1: ['host', 'r1', 'r2'],
                            r2: ['r1', 'r2', 'host']
                        };
                        var vals = _self.getStorage(_self);

                        /*status = 0 什么都不是
                         = 1 胡牌
                         = 2 杠
                         = 3 碰
                         * */
                        if(evtData.res==0) {
                            //默认操作
                            _self.displayCp(roles[urlData[1]], evtData, _self, true); //
                            var val = vals[2].data[0].playlist.payrest[0];
                            vals[2].data[0].playlist.payrest.splice(0, 1);
                            if(evtData.next==urlData[1]) {
                                var key = _self.getHoom();
                                _self.getcookie(vals, key);
                                var options = {
                                    type: 6,
                                    rid: rid
                                };
                                options = JSON.stringify(options);
                                ws.send(options);
                                //摸牌的逻辑
                                _self.Hupai(val, vals[2].data[0].playlist, urlData, evtData.next);
                                _self.templateMyOne(_self, val);
                            }
                        }else
                        if(evtData.res==1) {
                            //有人胡牌
                        }else
                        if(evtData.res==2) {
                            //有人杠
                        }else
                        if(evtData.res==3) {
                            //有人碰
                            if(evtData.cid) {
                                if (urlData[0]==evtData.next) {
                                    _self.templateLeft(_self,evtData,urlData,true);
                                }else if (urlData[2] == evtData.next) {
                                    _self.templateRight(_self,evtData,urlData,true);
                                }
                            }
                            _self.displayCp(roles[urlData[1]], evtData, _self, true); //

                        }else{
                            _self.peng(evtData,vals[2].data[0].playlist[urlData[1]],urlData[1],mid,roles,rid,_self);
                        }
                    }

                    if(evtData.type==6){
                        console.log('s')
                        var key = _self.getHoom()
                        var val = _self.getStorage(_self);
                        val[2].data[0].playlist.payrest.splice(0,1);
                        _self.getcookie(val,key);
                    }
                    if(evtData.type==8){
                        $('#over').css('display','block');
                    };
                }
        },
             peng : function(evtData,val,urlData,mid,next,rid,_slef){
                var status = _slef.checkstatus(evtData,val,urlData,mid,next,rid);
                var data = evtData.cid.split('-')[1];
                var cid = '';
                var id = '';
                for(var i=0;i<val.length;i++){
                    if(val[i].cate==data){
                        cid = val[i].type+val[i].cate;
                        id = val[i].id;
                    }
                }
                if(status==3) {
                    _slef.doms.blockpeng.css('display','block');
                    _slef.doms.blockpeng.find('img').on('click',function(){
                       if($(this).index()==0){
                           var options = {
                               type: 7,
                               rid: rid,
                               mid: mid,
                               cid: cid,
                               id: id,
                               next: urlData,
                               status: status,
                               role: urlData
                           };
                           options = JSON.stringify(options);
                           ws.send(options);
                           _slef.doms.blockpeng.css('display','none');
                           _slef.deletePeng(val,evtData,_slef,urlData)

                       }
                       if($(this).index()==1){
                           var options = {
                               type: 7,
                               rid: rid,
                               mid: mid,
                               cid: cid,
                               id: id,
                               next: evtData.next,
                               status: 0,
                               role: urlData
                           };
                           options = JSON.stringify(options);
                           ws.send(options);
                           _slef.doms.blockpeng.css('display','none');
                       }
                    });
                }else{
                    var options = {
                        type: 7,
                        rid: rid,
                        mid: mid,
                        cid: cid,
                        id: id,
                        next: evtData.next,
                        status: status,
                        role: urlData
                    };
                    options = JSON.stringify(options);
                    ws.send(options);
                }
        },
            deletePeng : function(data,val,_self,urldata){
                var deletedata = new Array();
                var val = val.cid.split('-')[1];
                for(var i=0;i<data.length;i++){
                    if(data[i].cate==val){
                        data.splice(i,1);
                        break
                    }
                }
                for(var i=0;i<data.length;i++){
                    if(data[i].cate==val){
                        data.splice(i,1);
                        break
                    }
                }

                _self.pengTemplate(data,_self,urldata);
                _self.deletepengtemplate(deletedata,_self)

            },
        deletepengtemplate : function(deletedata,_self){

            _self.doms.mypengPai.css('display','block');
            var text = '';
            var datagrid = deletedata;
            for (var i = 0; i < datagrid.length; i++) {
                text += '<li dataIndex=' + datagrid[i][0].id + ' data="' + datagrid[i][0].type + '-' + datagrid[i][0].cate + '">' +
                    '<img src="/home/imgs/' + datagrid[i][0].type + '-' + datagrid[i][0].cate + '.png" alt=""/>' +
                    '</li>'
            }
            _self.doms.mypengPai.append(text);
        },
        checkstatus : function(evtData,val,urlData,mid,next,rid,_slef){
            var data = evtData.cid.split('-')[1];
            var datas = data+data;
            var test = '';
            for(var i=0;i<val.length;i++){
                test += val[i].cate+'-'
            }
            var testarr = test.split('-');
            testarr.sort();
            test = '';
            for(var i=0;i<testarr.length;i++){
                if(testarr[i]!=''){
                    test += testarr[i]
                }
            }
            if(test.indexOf(datas)!=-1){
                return 3
            }
            return 0
        },
        overpais : function(obj,cid){

            if(cid.indexOf('-')!=-1) {
//           var text = $('.leftoverpais').html();
                var text = '';
                text += '<li>' +
                    '<img src="/home/imgs/' + cid + '_left.png" alt=""/>' +
                    '</li>';
                obj.append(text);
            }
        },
        str3 : function(str) {

           //提取连号字符串返回切割后的字符串和被切割的字符串

            var t = /(abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr){1}/;
            var b = str.replace(t.exec(str)[0],'');
            return {
                b : b,
                str : t.exec(str)[0]
            } ;
        },
        stridentical : function(str){

            //提取3个相同字符串返回切割后的字符串和被切割的字符串

            var t = /(aaa|bbb|ccc|ddd|eee|fff|ggg|hhh|iii|jjj|kkk|lll|mmm|nnn|ooo|ppp|qqq|rrr|sss|ttt|uuu){1}/;
            var b = str.replace(t.exec(str)[0],'');
            return{
                b : b,
                str : t.exec(str)[0]
            }
        },
        strTowDentical : function(){

            //提取2个相同字符串返回切割后的字符串和被切割的字符串

            var t = /(aa|bb|cc|dd|ee|ff|gg|hh|ii|jj|kk|ll|mm|nn|oo|pp|qq|rr|ss|tt|uu){1}/;
            var b = str.replace(t.exec(str)[0],'');
            return{
                b : b,
                str : t.exec(str)[0]
            }
        },
        Hupai : function(val,arr,urlData,next){   //胡牌自摸
            var p = arr[urlData[1]];
            p.push(val);
            var t = '';
            for(var i=0;i< p.length;i++){
                t+='.'+p[i].cate
            };
            var str = '';
            var arrt = t.split('.');
            var sortarr = arrt.sort();
            for(var i=0;i<sortarr.length;i++){
                if(sortarr[i]!=""){
                    str+=sortarr[i];
                }
            }
            var re = /(aa|bb|cc|dd|ee|ff|gg|hh|ii|jj|kk|ll|mm|nn|oo|pp|qq|rr|ss|tt|uu){7}/;
            var ifHupai = re.test(str);

//t[0]==t[1]&&t[2]==t[3]&&t[4]==t[5]&&t[6]==t[7]&&t[8]==t[9]&&t[10]==t[11]&&t[12]==t[13]
            if(urlData[1]==next){
                if(ifHupai){
                        $('#blockHupai').css('display','block')
                };
            }
        },
        addEvent : function(){
            var _self = this;
            _self.doms.MyPais.delegate('li','click',function(){   //摸进来的牌
                var s = this;  //点击的this
                if($(this).css('top')=='-20px'){
                    _self.chupai($(this));
                    setTimeout(function(){
                        _self.removePai(s,_self);
                        _self.setWidth();
                    },700);
                }else{
                    _self.doms.MyPai.find('li').animate({
                        marginTop : 0
                    });
                    _self.MyTop($(this),1);
                }
            });
            $('#blockHupai').on('click',function(){
                var urlData = w.location.href;
                urlData = urlData.split('?');
                var rid = urlData[1].split('&')[1].split('=')[1];
                var str = {
                    type : 8,
                    rid : rid
                };
                str = JSON.stringify(str);
                ws.send(str);
                $('#over').css('display','block');
            });
            _self.doms.MyPai.delegate('li','click',function(){  //本来的牌
                var s = this;  //点击的this
                if(_self.doms.mydata.css('display')=='block'){
                    if($(this).css('marginTop')=='-20px'){
                            _self.chupai($(this));
                        setTimeout(function(){
                            _self.removePai(s,_self,true);
                            _self.setWidth();
                        },700);

                    }else{
                        _self.doms.MyPais.find('li').animate({
                            top : 0
                        });
                        $(this).siblings().animate({
                            marginTop:0
                        });
                        _self.MyTop($(this));
                    }
                }
            })
        },
        displayCp : function(urlData,data,s,k,j){   //判断谁出牌

            if(k){
                if(j){
                    var index =  urlData.indexOf(data);
                }else{
                    var index = urlData.indexOf(data.next);
                }
                for (var i = 0; i < $('.dataId').length; i++) {
                    if ($('.dataId').eq(i).attr('tt') == index) {
                        $('.dataId').eq(i).css('display', 'block')
                    } else {
                        $('.dataId').eq(i).css('display', 'none')
                    }
                }
            }else {

                var zhuangjia = JSON.parse(data);
                console.log(zhuangjia.playlist.banker);
                var index = urlData.indexOf(zhuangjia.playlist.banker);
                for (var i = 0; i < $('.dataId').length; i++) {
                    if ($('.dataId').eq(i).attr('tt') == index) {
                        $('.dataId').eq(i).css('display', 'block')
                    } else {
                        $('.dataId').eq(i).css('display', 'none')
                    }
                }
            }
        },
        getHoom : function(){
            var urlData = w.location.href;
            var urlData = w.location.href;
            var rid = urlData.split('/')[urlData.split('/').length-2];
            var mid = urlData.split('/')[urlData.split('/').length-1];
            var pasId = urlData.split('/')[urlData.split('/').length-3];
            urlData = ['tels',urlData.split('/')[urlData.split('/').length-3]]
            return pasId+rid+mid

        },//获取房间号用户Id
        templateMy : function(_self,data,urlData,t,callback,removeSrot){  //  My的模板
            _self.doms.MyPai.html('');
            var data = JSON.parse(data);
            var datagrid = data.playlist[urlData];
            if(removeSrot!=undefined){
                var val = {
                    cate : $('.MyPais').find('li').attr('cate'),
                    id : $('.MyPais').find('li').attr('dataindex'),
                    name : $('.MyPais').find('li').attr('name'),
                    type : $('.MyPais').find('li').attr('type'),
                    val : $('.MyPais').find('li').attr('val')
                };
                if(val.cate!=undefined){
                    if(datagrid.length<13){
                        datagrid.push(val);
                    }
                }
            }
            var dataList = _self.getStorage(_self);
            dataList[2].data[0].playlist[urlData]= datagrid;
            var name = _self.getHoom();
            _self.getcookie(dataList,name);
            var text = '';
            data = _self.srot(data,urlData);
            if(data.playlist.banker==urlData) {
                if (t) {
                    for (var i = 0; i < datagrid.length; i++) {
                        text += '<li dataIndex=' + datagrid[i].id + ' data="' + datagrid[i].type + '-' + datagrid[i].cate + '">' +
                            '<img src="/home/imgs/' + datagrid[i].type + '-' + datagrid[i].cate + '.png" alt=""/>' +
                            '</li>'
                    }
                    callback && callback();
                } else {
                    for (var i = 0; i < datagrid.length - 1; i++) {
                        text += '<li dataIndex=' + datagrid[i].id + ' data="' + datagrid[i].type + '-' + datagrid[i].cate + '">' +
                            '<img src="/home/imgs/' + datagrid[i].type + '-' + datagrid[i].cate + '.png" alt=""/>' +
                            '</li>'
                    }
                    _self.templateMyOne(_self, datagrid[datagrid.length - 1], urlData[1]);
                }
            }else{
                if (t) {
                    for (var i = 0; i < datagrid.length; i++) {
                        text += '<li dataIndex=' + datagrid[i].id + ' data="' + datagrid[i].type + '-' + datagrid[i].cate + '">' +
                            '<img src="/home/imgs/' + datagrid[i].type + '-' + datagrid[i].cate + '.png" alt=""/>' +
                            '</li>'
                    }
                    callback && callback();
                } else {
                    for (var i = 0; i < datagrid.length; i++) {
                        text += '<li dataIndex=' + datagrid[i].id + ' data="' + datagrid[i].type + '-' + datagrid[i].cate + '">' +
                            '<img src="/home/imgs/' + datagrid[i].type + '-' + datagrid[i].cate + '.png" alt=""/>' +
                            '</li>'
                    }

                    $('.MyPais').find('li').remove();
                }
            }
            _self.doms.MyPai.append(text);
        },
        templateMyOne : function(_self,data,urlData){  //  摸进来的牌
            _self.doms.MyPais.html('');
            var text = '';
                text += '<li type='+data.type+' val='+data.val+' dataindex='+data.id+' cate='+data.cate+'  name='+data.name+'  data="'+data.type+'-'+data.cate+'">' +
                    '<img src="/home/imgs/'+data.type+'-'+data.cate+'.png" alt=""/>' +
                    '</li>'
            _self.doms.MyPais.append(text);
        },
        pengTemplate : function(data,_self,urlData){
            //碰牌的模板
            _self.doms.MyPai.html('');
            var datagrid = data;
            var text = '';
            for (var i = 0; i < datagrid.length; i++) {
                text += '<li dataIndex=' + datagrid[i].id + ' data="' + datagrid[i].type + '-' + datagrid[i].cate + '">' +
                    '<img src="/home/imgs/' + datagrid[i].type + '-' + datagrid[i].cate + '.png" alt=""/>' +
                    '</li>'
            }
            _self.doms.MyPai.append(text);
            var dataList = _self.getStorage(_self);
            dataList[2].data[0].playlist[urlData]= datagrid;
            var name = _self.getHoom();
            _self.getcookie(dataList,name);
            _self.setWidth();
        },
        templateLeft : function(_self,data,urlData,peng){  //左边的牌模板
            if(peng){
                _self.doms.leftPais.find('li').eq(0).remove();
                _self.doms.leftPais.find('li').eq(1).remove();
                var datagrid = new Array();
                data = data.cid.replace(data.cid.substring(data.cid.length-1),'-'+data.cid.substring(data.cid.length-1));
                for(var i=0;i<2;i++){
                    datagrid.push(data);
                }
                var text = '';
                for (var i = 0; i < datagrid.length; i++) {
                    text += '<li class="leftPai dao">' +
                        '<img src="/home/imgs/' + datagrid[i] +'_left.png" alt=""/>' +
                        '</li>'
                }
                _self.doms.leftPais.append(text);
            }else {
                _self.doms.leftPais.html('');
                var data = JSON.parse(data);
                var datagirid = data.playlist[urlData];
                var text = '';
                for (var i = 0; i < datagirid.length; i++) {
                    text += '<li class="leftPai">' +
                        '<img src="/home/imgs/pai_left.png" alt=""/>' +
                        '</li>'
                }
                _self.doms.leftPais.append(text);
            }
        },
        templateRight : function(_self,data,urlData,peng){ //右边的牌
            if(peng){
                _self.doms.RightPais.find('li').eq(0).remove();
                _self.doms.RightPais.find('li').eq(1).remove();
                var datagrid = new Array();
                data = data.cid.replace(data.cid.substring(data.cid.length-1),'-'+data.cid.substring(data.cid.length-1));
                for(var i=0;i<2;i++){
                    datagrid.push(data);
                }
                var text = '';
                for (var i = 0; i < datagrid.length; i++) {
                    text += '<li class="RightPai dao">' +
                        '<img src="/home/imgs/' + datagrid[i] +'_left.png" alt=""/>' +
                        '</li>'
                }
                _self.doms.RightPais.append(text);
            }else {
                _self.doms.RightPais.html('');
                var data = JSON.parse(data);
                var datagirid = data.playlist[urlData];
                var text = '';
                for (var i = 0; i < datagirid.length; i++) {
                    text += '<li class="RightPai">' +
                        '<img src="/home/imgs/pai_Right.png" alt=""/>' +
                        '</li>'
                }
                _self.doms.RightPais.append(text);
            }
        },
        time : function(){   //倒计时
            var _self = this;
            var initTime = _self.doms.time.html();
            var clearTime = setInterval(function(){
                initTime--;
                if(initTime<10){
                    _self.doms.time.css('marginLeft','-5.5px')
                }
                if(initTime<0){
                    clearInterval(clearTime);
                }else{
                _self.doms.time.html(initTime);
                }
            },1000)
        },
        MyTop : function(obj,v){   //点击第1下的时候移出去
            if(v){
                obj.animate({
                   top: '-20px'
                },100)
            }else {
                obj.animate({
                    marginTop: '-20px'
                }, 100)
            }
        },
        chupai : function(obj){   //点击第二下的时候移出去
            obj.animate({
                  marginTop : '-100px',
                  opacity : '0'
            });
        },
        removePai : function(obj,_self,t){ //点击第二下的时候删除

            _self.storage(obj,_self);
            obj.remove();
            var storageVal = _self.getStorage(_self);
            _self.palySize(storageVal[0].jsonList,_self);
//            var audio = _self.doms.audio.attr('src');  //音频
//            audio = audio.replace('null','10');
//            _self.doms.audio.attr('src',audio);
            var urlData = w.location.href;
            var rid = urlData.split('/')[urlData.split('/').length-2];
            var mid = urlData.split('/')[urlData.split('/').length-1];
            var pasId = urlData.split('/')[urlData.split('/').length-3];
            urlData = ['tels',urlData.split('/')[urlData.split('/').length-3]]
            var ts = urlData;
            var roles = {
                host: ['r2', 'host', 'r1'],
                r1: ['host', 'r1', 'r2'],
                r2: ['r1', 'r2', 'host']
            };

            var cp = roles[urlData[1]][2];
            var urlData = roles[urlData[1]];
            _self.displayCp(urlData,cp,_self,true,true);
            var removeIndex = $(obj).attr('dataindex');
            var dataList = _self.getStorage(_self);
            var arrList = dataList[2].data[0].playlist[ts[1]];
            for(var i=0;i<arrList.length;i++){
                if(arrList[i].id==removeIndex){
                    arrList.splice(i,1)
                }
            };

            dataList[2].data[0].playlist[ts[1]]=arrList;
            dataList = dataList[2].data[0];
            dataList = JSON.stringify(dataList);
            if(t){
                _self.templateMy(_self,dataList,urlData[1],true,function(){
                    $('.MyPais').find('li').remove();
                },'removeSrot')

            }
        },
        Shuffle : function(){  //打完牌后的数据清洗
            var _self = this;
            _self.templateMy();
        },
        ponstSend : function(obj){   //给家昌发送数据
            ws.send(obj);
        },
        setWidth : function(){
            var _self = this;
            _self.doms.MyPai.css('marginLeft','-'+_self.doms.MyPai.find('li').length*6/2+'%')
        },
        storage : function(obj,_self){   //储牌已经打出的牌
                var storageVal = _self.getStorage(_self);
                storageVal[0].jsonList.push($(obj).attr('data'));
                var urlData = w.location.href;
                var rid = urlData.split('/')[urlData.split('/').length-2];
                var mid = urlData.split('/')[urlData.split('/').length-1];
                var pasId = urlData.split('/')[urlData.split('/').length-3];
                urlData = ['tels',urlData.split('/')[urlData.split('/').length-3]]

                var roles = {
                    host : ['r2','host','r1'],
                    r1 : ['host','r1','r2'],
                    r2 : ['r1','r2','host']
                };
                urlData =  roles[urlData[1]];
                var jsonId = {
                      role :pasId,
                      rid : rid,
                      mid : mid,
                      cid : $(obj).attr('data'),
                      id :  $(obj).attr('dataindex'),
                      type : 5,
                      next : urlData[urlData.length-1]
                };
                jsonId = JSON.stringify(jsonId);
                _self.ponstSend(jsonId);  //给家昌发送打出去的牌
                var key = _self.getHoom();
                _self.getcookie(storageVal, key);
        },
        getStorage : function(_self){  //读取本地数据
            var key = _self.getHoom();
            var jsonList = localStorage.getItem(key);
            var arr = JSON.parse(jsonList);
            return arr
        },
        getcookie : function(val,name){
            localStorage.setItem(name,JSON.stringify(val))
        },
        setcookie : function(name){
            var jsonList = localStorage.getItem(name);
            jsonList = JSON.parse(jsonList);
            return jsonList
        },
        palySize : function(val,_self){
            _self.doms.mplay.html('');
            var text = '';
            for(var i=0;i<val.length;i++){
                text += '<li>' +
                       '<img src="/home/imgs/'+val[i]+'_center.png" alt=""/>' +
                       '</li>'
            }
            _self.doms.mplay.append(text);
        },
        clearStorage : function(obj){ //清空本地存储
            localStorage.setItem(obj,'undefined');
        },
        srot : function(arr,urlData){ //排序
            var datagrid = arr.playlist[urlData];
            for(var i=0;i<datagrid.length;i++){
                for(var j=i+1;j<datagrid.length;j++){
                    if(datagrid[i].type>datagrid[j].type){
                        datagrid[j] = datagrid.splice(i,1,datagrid[j])[0];
                    }
                }
            }
            for(var i=0;i<datagrid.length;i++){
                for(var j=i+1;j<datagrid.length;j++){
                    if(datagrid[i].type == datagrid[j].type){
                        if(datagrid[i].val >datagrid[j].val){
                            datagrid[j] = datagrid.splice(i,1,datagrid[j])[0];
                        }
                    }
                }
            }
            return arr;
        }
    };
    opt.init();

})(window);